package com.fractalist.base.core.web.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.fractalist.base.core.constants.SystemConstants;
import com.fractalist.base.core.web.BaseActionSupport;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 
 * 在sturts.xml中配置的过滤器，如果没登陆则跳转到指定地址
 * 
 * @author radio
 * 
 */
public class LoginInterceptor implements Interceptor {
	private String basePath;
	private String baseAllPath;
	/**
	 * 需要在sturts.xml中配置拦截器时进行配置的要跳转到的路径地址
	 */

	private static final long serialVersionUID = -4911122707518868115L;

	public void destroy() {
	}

	public void init() {
	}

	/**
	 * 拦截action，从session中取出userID，如果不存在则立刻跳转到指定的地址
	 */
	@SuppressWarnings("rawtypes")
	public String intercept(ActionInvocation ai) throws Exception {

		ActionContext ac = ai.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) ac
				.get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ac
				.get(ServletActionContext.HTTP_RESPONSE);

		if (null == basePath || basePath.length() <= 0) {
			basePath = request.getContextPath();
		}
		if (null == baseAllPath || baseAllPath.length() <= 0) {
			baseAllPath = request.getScheme() + "://" + request.getServerName()
					+ ":" + request.getServerPort() + basePath;
		}

		Map<String, Object> map = ac.getParameters();
		Map tempMap = (Map) map.get("paramMap");

		Object objPar = null;
		try {
			objPar = tempMap.get("params");
		} catch (Exception ex) {
			objPar = null;
		}

		HttpSession session = request.getSession();
		Object obj = (Object) session
				.getAttribute(SystemConstants.USER_SESSION_KEY);
		if (null == obj) {
			if (null == objPar) {
				// 表示采用的是非json+ajax请求
				request.getRequestDispatcher(
						basePath + "/admin/viewLogin.action").forward(request,
						response);
				return null;
			} else {
				// 表示采用的是ajax请求
				StringBuilder sbb = new StringBuilder();
				sbb.append("{'data':{'url':'");
				sbb.append(baseAllPath + "/login.jsp");
				sbb.append("'},'error':{'code':0,'msg':'session out'},'page':null}");
				ServletActionContext.getResponse().getWriter()
						.write(sbb.toString());
				return null;
			}
		} else {
			Object obj1 = ai.getProxy().getAction();
			if (obj1 instanceof BaseActionSupport) {
				BaseActionSupport bas = (BaseActionSupport) obj1;
				bas.setMethodName(ai.getProxy().getMethod());
			}
			return ai.invoke();
		}
	}

}